package com.xci.core.configuration;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.collect.Lists;
import com.xci.core.setting.SwaggerSetting;
import com.xci.sys.api.ParamApiController;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Api 接口文档自动配置
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI //增强功能
@ConditionalOnProperty(name = "xci.swagger.enabled", havingValue = "true")
public class SwaggerConfig {
    @Resource
    private SwaggerSetting swaggerSetting;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(swaggerApiInfo())
                .groupName(swaggerSetting.getGroupName())
                .useDefaultResponseMessages(false)
                // .consumes(Set.of(MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_FORM_URLENCODED_VALUE))
                // .produces(Set.of(MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_OCTET_STREAM_VALUE))
                .select()
                .apis(RequestHandlerSelectors.basePackage(ParamApiController.class.getPackage().getName()))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(Lists.newArrayList());
    }

    @Bean
    public ApiInfo swaggerApiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerSetting.getTitle())
                .description(swaggerSetting.getDescription())
                .termsOfServiceUrl(swaggerSetting.getTermsOfServiceUrl())
                .license(swaggerSetting.getLicense())
                .licenseUrl(swaggerSetting.getLicenseUrl())
                .contact(new Contact(swaggerSetting.getContactName(), swaggerSetting.getContactUrl(), swaggerSetting.getContactEmail()))
                .version(swaggerSetting.getVersion())
                .build();
    }
}